import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import * as api from './api';
import moment from 'moment';
import {expenseAdjustmentBillSourceType} from '../Enum';
export const SET_DEFAULT_BRANDID = 'SET_DEFAULT_BRANDID';
export const setDefaultBrandId = (data = []) => dispatch => {
    if(data.length === 1)
        return dispatch({
            type: SET_DEFAULT_BRANDID,
            id: data[0].id
        });
    return null;
};
/*==============================初始化API================================= */
export const GET_INIT_BEGIN = 'GET_INIT_BEGIN';
export const GET_INIT_SUCCESS = 'GET_INIT_SUCCESS';
export const GET_INIT_FAIL = 'GET_INIT_FAIL';
export const getInitDataBegin = () => ({
    type: GET_INIT_BEGIN
});
export const getInitDataSuccess = data => ({
    type: GET_INIT_SUCCESS,
    data,
});
export const getInitDataFail = () => ({
    type: GET_INIT_FAIL,
});
export const getInitData = (code = PAGE_CODE) => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.initQuery().then(res => {
        if(res.ok) {
            dispatch(setDefaultBrandId(res.data.content));
            dispatch(getInitDataSuccess(res.data));
        } else
            dispatch(getInitDataFail());
        return res.ok;
    });
    const permissions = getCurrentUserPagePermissionsApi(code).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return Promise.all([init, permissions]).then(values => values[0] && values[1]);
};
/*==============================查询列表================================= */

export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition
});
export const getListFail = () => ({
    type: GET_LIST_FAIL,
}); //获取列表

export const getList = condition => dispatch => {
    const {createTime, dealerCode, dealerName, ...props} = condition;
    if(createTime && createTime.length > 0) {
        props.beginCreateTime = moment(createTime[0]).toISOString();
        props.endCreateTime = moment(createTime[1]).toISOString();
    }
    dispatch(getListBegin());
    return api.getList(props).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
        return res.ok;
    });
}; //按钮搜索

export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    dispatch(getList(condition));
}; //分页排序搜索

export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

/*=============================作废================================= */
export const onClickAbandon = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.abandonInfo(id, {
        rowVersion
    }).then(res => res.ok);
};

/*=============================提交================================= */
export const onClickSubmit = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.submitInfo(id, {
        rowVersion
    }).then(res => res.ok);
};

/*=============================上报财务================================= */
export const onClickReportFinance = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.reportFinanceInfo(id, {
        rowVersion
    }).then(res => res.ok);
};
/*==============================导出================================= */
export const exportData = () => (dispatch, getState) => {
    const queryCondition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    const {createTime, pageIndex, pageSize, isDesc, sortField, dealerCode, dealerName, ...props} = queryCondition;
    if(createTime && createTime.length > 0) {
        props.beginCreateTime = moment(createTime[0]).toISOString();
        props.endCreateTime = moment(createTime[1]).toISOString();
    }
    return api.exportInfo(props);
};

/*==============================查询action================================= */
//修改查询条件

export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
//重置查询条件

export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});


/* =======================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN
});
export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data
});
export const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});

export const getDetail = id => dispatch => {
    dispatch(getDetailBegin());
    return api.getDetail(id).then(res => {
        if(res.ok)
            dispatch(getDetailSuccess(res.data));
        else
            dispatch(getDetailFail());
        return res.ok;
    });
};

export const getEditInit = id => (dispatch, getState) => {
    const brands = getState().getIn(['page', 'domainData', 'initData', 'brands']).toJS() || [];
    if(!id)
        return dispatch(setDefaultBrandId(brands));
    return dispatch(getDetail(id));
};
/* =======================详情页作废================================== */
export const onClickAbandonForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.abandonInfo(id, {
        rowVersion
    });
};

/* =======================详情页提交================================== */
export const onClickSubmitForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.submitInfo(id, {
        rowVersion
    });
};
/*==============================清除数据================================= */
export const CLEAR_DATA = 'CLEAR_DATA';
export const clearData = () => ({
    type: CLEAR_DATA
});

/*=============================审核================================= */
export const onClickApprove = (id, data) => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    const {isApproved, ...props} = data;
    if(isApproved)
        return api.passInfo(id, {
            ...props,
            rowVersion
        }).then(res => res.ok);
    return api.rejectInfo(id, {
        ...props,
        rowVersion
    }).then(res => res.ok);
};

/*=============================确认Pi================================= */
export const onClickConfirmPi = (id, data) => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    const {isConfirmed, ...props} = data;
    if(isConfirmed)
        return api.passPiInfo(id, {
            ...props,
            rowVersion
        }).then(res => res.ok);
    return api.rejectPiInfo(id, {
        ...props,
        rowVersion
    }).then(res => res.ok);
};

/*=============================确认================================= */
export const onClickConfirm = id => (dispatch, getState) => {
    const {rowVersion, piAttachments = []} = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    return api.confirmInfo(id, {
        rowVersion,
        piAttachments
    });
};

/*=============================多级审核================================= */
export const onClickMoreApprove = (id, data) => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    const {isApproved, ...props} = data;
    if(isApproved)
        return api.morePassInfo(id, {
            ...props,
            rowVersion
        }).then(res => res.ok);
    return api.moreRejectInfo(id, {
        ...props,
        rowVersion
    }).then(res => res.ok);
};
/*==========================修改新增编辑页数据================================= */
export const SAVE_SUBMIT_CONDITION = 'SAVE_SUBMIT_CONDITION';
export const saveSubmitCondition = (name, value) => ({
    type: SAVE_SUBMIT_CONDITION,
    name,
    value
});
export const onSubmit = id => (dispatch, getState) => {
    const {
        brandId,
        dealerId,
        direction,
        sourceType,
        reason,
        remark,
        laborFee = 0,
        materialFee = 0,
        mgmtFee = 0,
        rowVersion,
        otherFee,
        assistantFee,
        details,
        attachments = []
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    if(id)
        return api.updateInfo(id, {
            reason,
            remark,
            rowVersion,
            attachments,
            details: details.map(v => ({
                sourceId: v.sourceId,
                laborFee: v.laborFee,
                materialFee: v.materialFee,
                mgmtFee: v.mgmtFee,
                otherFee: v.otherFee,
                assistantFee: v.assistantFee,
            }))
        });
    return api.addInfo({
        brandId,
        dealerId,
        direction,
        sourceType,
        reason,
        remark,
        laborFee,
        materialFee,
        mgmtFee,
        otherFee,
        assistantFee,
        attachments,
        details: details.map(v => ({
            sourceId: v.sourceId,
            laborFee: v.laborFee,
            materialFee: v.materialFee,
            mgmtFee: v.mgmtFee,
            otherFee: v.otherFee,
            assistantFee: v.assistantFee,
        }))
    });
};


export const UPDATE_ATTACHMENTS = 'UPDATE_ATTACHMENTS';
export const updateAttachments = data => ({
    type: UPDATE_ATTACHMENTS,
    data: {
        fileId: data.id,
        fileName: data.fileName
    }
});

export const REMOVE_ATTACHMENTS = 'REMOVE_ATTACHMENTS';
export const removeAttachments = id => ({
    type: REMOVE_ATTACHMENTS,
    id
});

export const UPDATE_PIATTACHMENTS = 'UPDATE_PIATTACHMENTS';
export const updatePiAttachments = data => ({
    type: UPDATE_PIATTACHMENTS,
    data: {
        fileId: data.id,
        fileName: data.fileName
    }
});

export const REMOVE_PIATTACHMENTS = 'REMOVE_PIATTACHMENTS';
export const removePiAttachments = id => ({
    type: REMOVE_PIATTACHMENTS,
    id
});
export const SELECT_DATA = 'SELECT_DATA';
export const selectData = data => ({
    type: SELECT_DATA,
    data
});


export const SELECT_DEALER = 'SELECT_DEALER';
export const selectDealer = data => (dispatch, getState) => {
    const {brandId, id, code, rowVersion, options, attachments, details} = getState().getIn(['page', 'appState', 'submitData']).toJS() || {};
    const condition = {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
        currency: data.currency,
        id,
        brandId,
        code,
        rowVersion,
        options,
        attachments,
        details
    };
    dispatch({
        type: SELECT_DEALER,
        data: condition
    });
};

export const selectBrand = value => (dispatch, getState) => {
    const {dealerId, dealerCode, dealerName, id, code, rowVersion, options, attachments, details} = getState().getIn(['page', 'appState', 'submitData']).toJS() || {};
    const condition = {
        dealerId,
        dealerCode,
        dealerName,
        id,
        brandId: value,
        code,
        rowVersion,
        options,
        attachments,
        details
    };
    dispatch({
        type: SELECT_DEALER,
        data: condition
    });
};

export const selectSourceType = (name, value) => dispatch => {
    const condition = {
        [name]: value,
        laborFee: 0,
        materialFee: 0,
        mgmtFee: 0,
        otherFee: 0,
        assistantFee: 0,
        totalFee: 0,
        details: []
    };
    dispatch(selectData(condition));
};

export const SELECT_DEALER_QUERY = 'SELECT_DEALER_QUERY';
export const selectDealerQuery = data => ({
    type: SELECT_DEALER_QUERY,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});

export const UPDATE_DETAILS = 'UPDATE_DETAIL';
export const updateDetails = (details, data) => ({
    type: UPDATE_DETAILS,
    data,
    details
});

export const DELEDT_DETAILS = 'DELEDT_DETAILS';
export const deleteDetails = id => ({
    type: DELEDT_DETAILS,
    id
});
export const DELEDT_DETAILS_ALL = 'DELEDT_DETAILS_ALL';
export const deleteDetailsAll = () => ({
    type: DELEDT_DETAILS_ALL
});

export const selectDetails = data => dispatch => {
    const conditions = data.map(item => ({
        sourceId: item.id,
        sourceCode: item.code,
        vin: item.vin,
        productCategoryCode: item.productCategoryCode,
        laborFee: item.laborFee || 0,
        materialFee: item.materialFee || 0,
        mgmtFee: item.mgmtFee || 0,
        otherFee: item.otherFee || 0,
        assistantFee: item.assistantFee || 0,
        totalFee: (item.laborFee || 0) + (item.materialFee || 0) + (item.mgmtFee || 0) + (item.otherFee || 0) + (item.assistantFee || 0)
    }));
    dispatch(updateDetails(conditions));
};
// 编辑备件清单
export const SAVE_DETAILS = 'SAVE_DETAILS';
export const saveDetails = data => ({
    type: SAVE_DETAILS,
    data,
});

